<template>
  <div style="margin-top: 5px">
    <el-row :style="{height: conmpontHeight+'px'}" :gutter="10">
      <el-col :span="12" style="overflow: hidden">
        <el-form ref="role"
                 :model="roleForm"
                 label-position="right"
                 label-width="80px"
                 :rules="rules.role"
                 :hide-required-asterisk=true
                 :class="{animated:roleShake,shake:roleShake}"
                 :inline="true">
          <el-form-item label="角色名" prop="name">
            <el-autocomplete
              v-model="roleForm.name"
              :fetch-suggestions="roleFilter"
              placeholder="请输入内容"
              @select="roleSelect">
              <el-button slot="append" type="info" :disabled="searchdisabled" @click="roleSearch" icon="el-icon-search"
                         size="mini">查询
              </el-button>
            </el-autocomplete>
          </el-form-item>
        </el-form>

        <div :style="{height: (conmpontHeight-60)+'px'}">
          <el-scrollbar style="height: 100%;width: 100%;overflow-x: hidden">
            <el-tree
              ref="roleTree"
              :data="roleTree"
              show-checkbox
              node-key="id"
              accordion
              :filter-node-method="roleTreeFilter"
              @check="roleTreeSelect">
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>

      <el-col :span="12" style="overflow: hidden">
        <el-form ref="permission"
                 :model="permissionForm"
                 label-position="right"
                 label-width="80px"
                 :rules="rules.permission"
                 :hide-required-asterisk=true
                 :inline="true">
          <el-form-item label="权限名称" prop="name" :class="{animated:permissionShake,shake:permissionShake}">

            <el-autocomplete
              v-model="permissionForm.name"
              :fetch-suggestions="permissionFilter"
              placeholder="请输入内容">
              <el-button slot="append" type="info" :disabled="searchdisabled" @click="permissionSearch" icon="el-icon-search" size="mini">查询</el-button>
            </el-autocomplete>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button-group>
              <el-button type="primary" plain :disabled="searchdisabled" @click="updateRole" icon="el-icon-circle-plus" size="small">保存</el-button>
              <el-button type="info" plain :disabled="searchdisabled" @click="rest" icon="el-icon-error" size="small">取消</el-button>
              <el-popover
                placement="bottom"
                title="使用说明"
                width="200"
                trigger="hover">
                <div style="margin-left: 10px">
                  <ol>
                    <li>角色名可以过滤选择</li>
                    <li>权限名称可以过滤选择</li>
                  </ol>
                </div>
                <el-button slot="reference" type="success" icon="el-icon-bell"></el-button>
              </el-popover>
            </el-button-group>
          </el-form-item>
        </el-form>
        <div :style="{height: (conmpontHeight-60)+'px'}">
          <el-scrollbar style="height: 100%;overflow-x: hidden">
            <el-tree
              ref="permissionTree"
              :data="permissionTree"
              show-checkbox
              node-key="id"
              :filter-node-method="permissionTreeFilter">
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { getRolesLikeName, GetRoleTree } from '@/api/sysrole'
  import { GetPermissionLikeName, GetPermissionTree, GetPermissionTreeByPermissionIds } from '@/api/sysPersimmon'
  import { GetPermissionByRoleId,UpdateRolePermission } from '@/api/sysRolePermission'
    export default {
        mounted() {
          // 获取main高度
          let parHeight = this.$parent.$parent.$el.offsetHeight
          console.log('parHeight',parHeight)
          this.conmpontHeight = parHeight - 60 - 34
          GetRoleTree('').then(res => {
            this.roleTree = res.data
          })

          GetPermissionTree().then(res => {
            this.permissionTree = res.data
            console.log('res.data',res.data)
          })
        },
      data(){
          return {
            searchdisabled: false,
            conmpontHeight: 0,
            roleForm: {
              name: ''
            },
            roleShake: false,
            rules: {
              role: {
                name: [
                  { required: true, message: '请选择', trigger: 'change' }
                ]
              },
              permission: {
                name: [
                  { required: true, message: '请选择', trigger: 'blur' }
                ]
              }
            },
            roleTree: [],
            permissionForm: {
              name: ''
            },
            permissionShake: false,
            permissionTree: [],
            permissionOpt: [],
            permissionBeforeSave: []
          }
      },
      methods:{
        roleFilter(roleName, cb) {
          getRolesLikeName(roleName).then(res => {
            this.roleOpt = res.data.map(obj => {
              return {
                label: obj.id,
                value: obj.name
              }
            })
            cb(this.roleOpt)
          })
        },
        roleSelect(item) {
          this.roleForm.name = item.value
          console.log('roleSelect', item)
        },
        roleSearch() {
          const that = this
          new Promise(function(resolve, reject) {
            that.roleShake = false
            that.searchdisabled = true
            resolve()
          }).then(() => {
            that.$refs.role.validate(valid => {
              if (valid) {
                that.$refs.roleTree.filter(this.roleForm.name)
              } else {
                that.roleShake = true
                that.$refs.roleTree.filter('')
              }
            })
            that.searchdisabled = false
          })
        },
        roleTreeFilter(value, data, node) {
          if (!value) return true
          return data.label.indexOf(value) !== -1
        },
        roleTreeSelect(data) {
          // 判断是否取消选择
          if (this.selectRole == data.id) {
            this.$refs.permissionTree.setCheckedNodes([])
            this.$refs.roleTree.setCheckedNodes([])
            this.selectRole = ''
          } else {
            this.$confirm('是否选择' + data.label, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              console.log('确定')
              this.$refs.roleTree.setCheckedNodes([data])
              this.selectRole = this.$refs.roleTree.getCheckedKeys()[0]
              console.log('this.selectRole',this.selectRole)

              GetPermissionByRoleId(this.selectRole).then(res => {
                console.log('GetPermissionByRoleId', res)

                const permissionIds = res.data.map(item => {
                  return item.permissionId
                })
                console.log('permissionIds', permissionIds)

                GetPermissionTreeByPermissionIds(permissionIds).then(res => {
                  if (res.data){
                    console.log('res.data', res.data)
                    this.$refs.permissionTree.setCheckedKeys(res.data)
                    const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
                    const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
                    this.permissionBeforeSave = [...halfCheckedKeys, ...checkedKeys].filter(keys => !isNaN(keys))
                  } else {
                    this.$message({
                      type: 'info',
                      message: '该角色没有权限'
                    })
                    this.$refs.permissionTree.setCheckedNodes([])
                  }

                })
              })
            }).catch(() => {
              console.log('取消')
              this.$message({
                type: 'info',
                message: '已取消'
              })
              this.$refs.permissionTree.setCheckedNodes([])
              this.$refs.roleTree.setCheckedNodes([])
              this.selectRole = ''
            })
          }
        },
        permissionFilter(permissionName, cb) {
          GetPermissionLikeName(permissionName).then(res => {
            this.permissionOpt = res.data.map(obj => {
              return {
                label: obj.id,
                value: obj.name
              }
            })
            cb(this.permissionOpt)
          })
        },
        permissionSearch() {
          const that = this
          new Promise(function(resolve, reject) {
            that.permissionShake = false
            that.searchdisabled = true
            console.log('click')
            resolve()
          }).then(() => {
            that.$refs.permission.validate(valid => {
              if (valid) {
                console.log('valid',valid)
                that.$refs.permissionTree.filter(this.permissionForm.name)
              } else {
                that.permissionShake = true
                that.$refs.permissionTree.filter('')
              }
            })
            that.searchdisabled = false
          })
        },
        updateRole() {
          console.log('this.$refs.roleTree.getCheckedKeys()',this.$refs.roleTree.getCheckedKeys())
          if (this.$refs.roleTree.getCheckedKeys().length===0) {
            this.$alert('未选择角色', '提示', {
              confirmButtonText: '确定'
            })
          }else {
            let checkedKeys = this.$refs.permissionTree.getCheckedKeys()
            let halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
            let filterKeys = [...checkedKeys, ...halfCheckedKeys].filter(key => !isNaN(key))
            let addPermission = filterKeys.filter(keys => this.permissionBeforeSave.indexOf(keys) === -1)
            let delPermission = this.permissionBeforeSave.filter(keys => filterKeys.indexOf(keys) === -1)
            let role= this.$refs.roleTree.getCheckedKeys()
            console.log('addPermission',addPermission)
            console.log('delPermission',delPermission)
            console.log('role',role)
            UpdateRolePermission(role,addPermission,delPermission).then(res=>{
              this.$message({
                type: 'success',
                message: '保存成功'
              })
            }).catch(error=>{
              this.$message({
                type: 'success',
                message: error
              })
            })
          }

        },
        rest() {
          this.$refs.permissionTree.setCheckedNodes([])
          this.$refs.roleTree.setCheckedNodes([])
          this.selectRole = ''
        },
        permissionTreeFilter(value, data, node) {


          if (!value) return true
          console.log('data.label',data.label)
          console.log('data.label.indexOf(value)',data.label.indexOf(value))
          return data.label.indexOf(value) !== -1
        }
      }
    }
</script>

<style>
  .el-scrollbar__wrap{
    overflow-x: auto;
  }
</style>
